<template>
	<div class="song-res">
		<div class="result">
			<div class="match" v-if="Object.keys(matchSinger).length !== 0 || Object.keys(matchAlbum).length !== 0">
				<div class="goodMatch">
					<div class="matchitem" @click="goSingerdetail" v-if="Object.keys(matchSinger).length !== 0">
						<div class="cover">
							<img v-lazy="matchSinger.img1v1Url" alt="" />
						</div>
						<div class="iname">
							<span>歌手：{{ matchSinger.name }}</span>
							<span class="iconfont icon-xiayiye"></span>
						</div>
					</div>
					<div class="matchitem" @click="goAlbumdetail" v-if="Object.keys(matchAlbum).length !== 0">
						<div class="cover">
							<img v-lazy="matchAlbum.picUrl" alt="" />
						</div>
						<div class="iname">
							<span>专辑：{{ matchAlbum.name }}</span>
							<span class="iconfont icon-xiayiye"></span>
						</div>
					</div>
				</div>
			</div>
		</div>
		<SongTable :songs="songRes" />
		<Pagination :total="songResCount" :page-size="50" @handleCurrentChange="getSearchSongBy"/>
	</div>
</template>

<script setup>
/* 网络请求 */
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getSearchSong, getGoodMatch } from "@/network/searchdetail/searchdeatil";
import SongTable from "@/components/content/SongTable.vue";
// 声明响应式变量
const keywords = ref('');
const songRes = ref([]);
const songResCount = ref(0);
const matchSinger = ref({});
const matchAlbum = ref({});

// 获取路由参数
const route = useRoute();
const router= useRouter();
// 生命周期钩子，组件创建时执行
onMounted(() => {
  // 保存搜索的关键词
  keywords.value = route.params.keywords;
  // 获取搜索歌曲列表
  getSearchSongBy();
  // 获取最佳匹配结果
  getGoodMatchBy();
});

// 获取搜索歌曲列表
const getSearchSongBy = (page = 1) => {
  let offset = (page - 1) * 50;
  getSearchSong(keywords.value, offset).then(res => {
    songRes.value = res.data.result.songs;
    songResCount.value = res.data.result.songCount;
  });
};

// 获取最佳匹配结果
const getGoodMatchBy = () => {
  getGoodMatch(keywords.value)
    .then(res => {
      matchSinger.value = res.data.result.artist[0];
      matchAlbum.value = res.data.result.album[0];
    })
    .catch(err => console.error(err));
};

// 跳转到歌手详情页面
const goSingerdetail = () => {
  router.push("/singerdetail/" + matchSinger.value.id);
};

// 跳转到专辑详情页面
const goAlbumdetail = () => {
  router.push("/albumdetail/" + matchAlbum.value.id);
};
</script>

<style lang="less" scoped>
.result {
	padding: 10px 15px;
	h3 {
		padding-bottom: 10px;
	}
}
.goodMatch {
	padding: 5px 0;
	display: flex;
	cursor: pointer;
	.matchitem {
		width: 20%;
		display: flex;
		align-items: center;
		margin-right: 20px;
		border: 1px solid #dddddd;
		&:hover {
			font-weight: 700;
		}
		.cover {
			flex: 1;
			img {
				width: 100%;
			}
		}
		.iname {
			display: flex;
			justify-content: space-between;
			align-items: center;
			flex: 2;
			height: 100%;
			padding: 0 5px;
			background: #f5f5f5;
		}
	}
}
</style>
